<?php
namespace app\admin\logic;

use app\admin\model\Menu as menuModel;
use think\facade\Cache;
use think\facade\Db;

class Menu
{
    /**
     * 获取用户的菜单
     *
     * @return json
     */
    public function getUserMenuList()
    {
        $menuModel = new menuModel;
        if(Cache::get(request()->header()['token']??'')['is_system'] == 1){
            $menu = $menuModel->order(['id', 'sort'])->select();
            $menu = $menu->toArray();
        }else{
            $roles = (new \app\admin\model\Role)->where('id', 'in', Cache::get(request()->header()['token']??'')['role_ids'])->where('site_id', Db::name('site')->where('host', str_replace('admin.', '', $_SERVER['HTTP_HOST']) ?? '')->value('id'))->column('permission_ids');
            $temp = [];
            foreach($roles as $v){
                $temp1 = array_merge($temp, json_decode($v, true));
                foreach($temp1 as $v){
                    $temp[] = $v;
                }
            }
            if(!$temp){
                return json_return('10000', '', []);
            }
            $permissions = (new \app\admin\model\Permission)->where('id', 'in', $temp)->column('DISTINCT controller');
            $ids = [];
            foreach($permissions as $v){
                $temp = (new \app\admin\model\Menu)->where("url regexp '^{$v}/'")->where('pid', '>', 0)->column('id');
                if($temp){
                    $ids[] = $temp[0];
                }
            }
            $submenu = $menuModel->where('id', 'in', $ids)->where('pid', '>', 0)->order(['sort', 'id'])->select()->toArray();
            if(!$submenu){
                return json_return('10000', '', []);
            }
            $subids = [];
            foreach($submenu as $v){
                $subids[] = $v['pid'];
            }
            $mainmenu = $menuModel->where('id', 'in', $subids)->order(['sort', 'id'])->select()->toArray();
            $menu = [];
            foreach($submenu as $v){
                $menu[] = $v;
            }
            foreach($mainmenu as $v){
                $menu[] = $v;
            }
        }
        $temp = [];
        foreach($menu as $v){
            if($v['pid'] == 0){
                $temp[$v['id']] = $v;
            }
        }
        foreach($menu as $v){
            if($v['pid'] != 0){
                if(empty($temp[$v['pid']]['sub'])){
                    $temp[$v['pid']]['sub'] = [];
                }
                $temp[$v['pid']]['sub'][$v['id']] = $v;
            }
        }
        return json_return('10000', '', $temp);
    }
}